# -*- coding: utf-8 -*-

import sys

from utils.pos import get_pos
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtCore import Qt, qAbs, QRect
from PyQt5.QtGui import QPen, QPainter, QColor, QGuiApplication, QFont


# 截图程序


class CaptureScreen(QWidget):
    # 初始化变量
    beginPosition = None
    endPosition = None
    fullScreenImage = None
    captureImage = None
    isMousePressLeft = None
    isLabelFollow = True
    painter = QPainter()
    # 区域坐标
    ScreenPos = get_pos()

    def __init__(self):
        super(CaptureScreen, self).__init__()
        self.initWindow()  # 初始化窗口
        self.captureFullScreen()  # 获取全屏
        self.label_message = QLabel(self)
        self.label_message.setStyleSheet('color: rgb(30, 144, 245)')
        self.label_message.setText(list(self.ScreenPos.keys())[0])

    def initWindow(self):
        self.setMouseTracking(True)  # 鼠标追踪
        self.setCursor(Qt.CrossCursor)  # 设置光标
        self.setWindowFlag(Qt.FramelessWindowHint)  # 窗口无边框
        self.setWindowState(Qt.WindowFullScreen)  # 窗口全屏
        # 设置窗口置顶和窗口无边框。
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)

    def captureFullScreen(self):
        self.fullScreenImage = QGuiApplication.primaryScreen().grabWindow(QApplication.desktop().winId())

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.beginPosition = event.pos()
            self.isMousePressLeft = True
            self.isLabelFollow = False
        if event.button() == Qt.RightButton:
            # 如果选取了图片,则按一次右键开始重新截图
            if self.captureImage is not None:
                self.reset()
            else:
                self.close()

    def mouseMoveEvent(self, event):
        if self.isMousePressLeft is True:
            self.endPosition = event.pos()
            self.update()
        elif self.isLabelFollow:
            self.label_message.move(event.pos().x(), event.pos().y() - self.label_message.height() - 3)

    def mouseReleaseEvent(self, event):
        self.endPosition = event.pos()
        self.isMousePressLeft = False

    def mouseDoubleClickEvent(self, event):
        if self.captureImage is not None:
            keys = list(self.ScreenPos.keys())
            key_sub = keys.index(self.label_message.text()) + 1

            if key_sub == len(keys):
                self.close()
                return
            key = keys[key_sub]
            self.label_message.setText(key)
            self.label_message.adjustSize()
            self.reset()

    #
    # def keyPressEvent(self, event):
    #     if event.key() == Qt.Key_Escape:
    #         self.close()
    #     if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
    #         if self.captureImage is not None:
    #             self.saveImage()
    #             self.close()

    # 重置画框
    def reset(self):
        self.captureImage = None
        self.paintBackgroundImage()
        self.isLabelFollow = True
        self.update()

    def paintBackgroundImage(self):
        shadowColor = QColor(0, 0, 0, 100)  # 黑色半透明
        self.painter.drawPixmap(0, 0, self.fullScreenImage)
        self.painter.fillRect(self.fullScreenImage.rect(), shadowColor)  # 填充矩形阴影
        # 重设窗口大小
        self.resize(self.fullScreenImage.size())

    def paintEvent(self, event):
        self.painter.begin(self)  # 开始重绘
        self.paintBackgroundImage()
        penColor = QColor(30, 144, 245)  # 画笔颜色
        self.painter.setPen(QPen(penColor, 1, Qt.SolidLine, Qt.RoundCap))  # 设置画笔,蓝色,1px大小,实线,圆形笔帽
        if self.isMousePressLeft is True:
            pickRect = self.getRectangle(self.beginPosition, self.endPosition)  # 获得要截图的矩形框
            self.captureImage = self.fullScreenImage.copy(pickRect)  # 捕获截图矩形框内的图片
            self.painter.drawPixmap(pickRect.topLeft(), self.captureImage)  # 填充截图的图片
            self.painter.drawRect(pickRect)  # 画矩形边框

            self.painter.setPen(QColor(168, 34, 3))
            self.painter.setFont(QFont('Decorative', 10))
            self.painter.drawText(pickRect, Qt.AlignCenter,
                                  'x:{},y:{},w:{},h:{}'.format(pickRect.x(), pickRect.y(), pickRect.width(),
                                                               pickRect.height()))
        self.painter.end()  # 结束重绘

    def getRectangle(self, beginPoint, endPoint):
        pickRectWidth = int(qAbs(beginPoint.x() - endPoint.x()))
        pickRectHeight = int(qAbs(beginPoint.y() - endPoint.y()))
        pickRectTop = beginPoint.x() if beginPoint.x() < endPoint.x() else endPoint.x()
        pickRectLeft = beginPoint.y() if beginPoint.y() < endPoint.y() else endPoint.y()
        pickRect = QRect(pickRectTop, pickRectLeft, pickRectWidth, pickRectHeight)
        # 避免高度宽度为0时候报错
        if pickRectWidth == 0:
            pickRect.setWidth(2)
        if pickRectHeight == 0:
            pickRect.setHeight(2)

        return pickRect

    def saveImage(self):
        self.captureImage.save('picture.png', quality=95)  # 保存图片到当前文件夹中


if __name__ == "__main__":
    app = QApplication(sys.argv)
    windows = CaptureScreen()
    windows.show()
    sys.exit(app.exec_())
